﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using CarCrash.Core.Model;
using CarCrash.Core.helper;

namespace CarCrash.Core.Services
{
    public abstract class GenericDaoService<T> where T : class
    {

        public ISession OpenSession() 
        {
            return NHibernateHelper.OpenSession();
        }

        public void CloseSession()
        {
            NHibernateHelper.CloseSession();
        }

        public void SaveOrUpdate(T t) 
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.SaveOrUpdate(t);
                transaction.Commit();
            }
        }

        public T GetById(int id)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            return session.Get<T>(id);
        }

        public IList<T> GetAll()
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            return session.CreateCriteria<T>().List<T>();
        }

        public void Delete(T t) 
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Delete(t);
                transaction.Commit();
            }
        }

    }
}